from sqlalchemy import Column, Integer, String, Index
from sqlalchemy.orm.session import Session

from airflow.models.base import Base
from airflow.utils.session import provide_session

'''
category 0 email, 1 dingding
'''


class Alert(Base):
    __tablename__ = "idata_alert"

    id = Column(Integer, primary_key=True, autoincrement=True)
    category = Column(Integer)
    name = Column(String(64))
    content = Column(String(255))

    __table_args__ = (
        Index('category_content', category, content),
    )

    @staticmethod
    @provide_session
    def get_alert(alert_id, session: Session = None):
        return session.query(Alert).filter(Alert.id == alert_id).first()

    @provide_session
    def insert(self, session: Session = None):
        session.add(self)

    @staticmethod
    @provide_session
    def query(category=None, session: Session = None):
        qry = session.query(Alert)
        if category:
            qry = qry.filter(Alert.category == category)
        return qry.all()

    @staticmethod
    @provide_session
    def query_page(page, per_page, category=None, session: Session = None):
        qry = session.query(Alert)
        if category:
            qry = qry.filter(Alert.category == category)
        return qry.paginate(page, per_page=per_page)

    @provide_session
    def update(self, session: Session = None):
        session.merge(self)

    def to_json(self):
        data = {'id': self.id, 'category': self.category, 'name': self.name, 'content': self.content}
        return data
